import { resolve } from 'path';
import { loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import { createHtmlPlugin } from 'vite-plugin-html';
import Unocss from 'unocss/vite';
import AutoImport from 'unplugin-auto-import/vite'; //按需自动加载API插件
import Components from 'unplugin-vue-components/vite'; //按需自动加载组件
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';
import type { UserConfig, ConfigEnv } from 'vite';

function pathResolve(dir: string) {
  return resolve(__dirname, '.', dir);
}

// https://vitejs.dev/config/
export default ({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const { VITE_APP_TITLE, VITE_OUT_DIR, VITE_PORT, VITE_PUBLIC_PATH, VITE_APP_PROXY } = env;

  return {
    base: VITE_PUBLIC_PATH,
    resolve: {
      alias: {
        '/@': pathResolve('src'),
        '/@views': pathResolve('src/views'),
        '/@components': pathResolve('src/components'),
        '/@types': pathResolve('src/types'),
        // store: pathResolve('src/store'),
      },
    },
    server: {
      open: true,
      port: Number(VITE_PORT),
      host: '0.0.0.0', // ← 新增内容 ←
      hmr: {
        overlay: true,
      },
      proxy: {
        '/api': {
          target: VITE_APP_PROXY,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },

    build: {
      outDir: VITE_OUT_DIR,
      sourcemap: true,
      chunkSizeWarningLimit: 2000,
      minify: 'terser', //压缩方式
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
    },
    optimizeDeps: {
      include: ['ant-design-vue/es/locale/zh_CN', '@ant-design/icons-vue', 'echarts'],
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            hack: `true; @import (reference) "${resolve('src/assets/styles/abstracts/index.less')}";`,
          },
          javascriptEnabled: true,
        },
      },
    },
    plugins: [
      vue(),
      Unocss(),
      AutoImport({
        dts: './src/auto-imports.d.ts',
        imports: [
          'vue',
          'vue-router',
          'pinia',
          {
            'ant-design-vue': ['message', 'notification'],
            '/@/serve/request': ['get', 'post', 'del', 'put'],
            '/@/store': ['useStore'],
          },
        ],
      }),
      Components({
        directoryAsNamespace: true, //解决命名冲突
        dirs: ['src/components'],
        dts: './src/auto-components.d.ts',
        resolvers: [
          AntDesignVueResolver({
            importStyle: false, // css in js
          }),
        ],
      }),
      createHtmlPlugin({
        minify: mode === 'production',
        inject: {
          data: {
            title: VITE_APP_TITLE,
          },
        },
      }),
    ],
  };
};
